//
//  SearchHouseViewController.m
//  House
//
//  Created by 张垚 on 16/6/24.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

#import "SearchHouseViewController.h"

#import "MySearchBar.h"
#import "MyNavigationBar.h"
#import "ImageViewAndLabelView.h"

#import "RentHouseListNoSlideTableViewCell.h"
#import "SecondaryHouseListNoSlideTableViewCell.h"
#import "AgentListNoSlideTableViewCell.h"
#import "ApartmentHotelListTableViewCell.h"

#import "RentHouseListModel.h"
#import "SecondaryListModel.h"
#import "AgentListModel.h"
#import "ApartmentHotelListModel.h"

#import "SecondaryDetailViewController.h"
#import "RentHouseDetailViewController.h"
#import "AgentDetailViewController.h"
#import "ApartmentHotelDetailViewController.h"

@interface SearchHouseViewController ()<UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *searchListTableView;

@property (nonatomic, copy) NSString *str;
//添加数据的数据
@property (nonatomic, strong) NSMutableArray *dataArr;
//当前请求数据的页数
@property (nonatomic, assign) NSInteger page;
//是否搜索文本
@property (nonatomic, assign) NSInteger searchTextTag;


@end
//cell重用标识符
static NSString *rentHouseCellID = @"RentHouseListNoSlideTableViewCellID";
static NSString *secondaryHouseCellID = @"SecondaryHouseListNoSlideTableViewCellID";
static NSString *AgentCellID = @"AgentListNoSlideTableViewCellID";
static NSString *ApartmentHotelCellID = @"ApartmentHotelListTableViewCellID";
//url
static NSString *rentHouseUrlStr = @"http://aizufang.hrbzjwl.com/tp/api.php/Rent/index/";
static NSString *secondaryUrlStr = @"http://aizufang.hrbzjwl.com/tp/api.php/iosapp/asecondary/";
static NSString *hotelUrlStr = @"http://aizufang.hrbzjwl.com/tp/api.php/Gongyujd/index/";
static NSString *agentUrlStr = @"http://aizufang.hrbzjwl.com/tp/api.php/Jingjiren/index/";



@implementation SearchHouseViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.tabBarController.tabBar.hidden = NO;
}
#pragma mark - 主程序入口
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    //页数 标签初始化为1
    _page = 1;
    _searchTextTag = 1;
    _dataArr = [NSMutableArray array];
    //顶部视图创建
    MyNavigationBar *navigationBar = [[MyNavigationBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    [navigationBar.cancelButton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    navigationBar.mySearchBar.textFiled.placeholder = @"请输入搜索内容";
    navigationBar.mySearchBar.textFiled.delegate = self;
   [self.view addSubview:navigationBar];
    //[self creatMainView];
    [self initTableView];
    // Do any additional setup after loading the view.
}
//返回上一视图
- (void)back:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - tableview
//初始化 签协议
- (void)initTableView {
    _searchListTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64) style:UITableViewStylePlain];
    _searchListTableView.tableFooterView = [UIView new];
    [self.view addSubview:_searchListTableView];
    _searchListTableView.delegate = self;
    _searchListTableView.dataSource = self;
    [_searchListTableView registerClass:[RentHouseListNoSlideTableViewCell class] forCellReuseIdentifier:rentHouseCellID];
    [_searchListTableView registerClass:[SecondaryHouseListNoSlideTableViewCell class] forCellReuseIdentifier:secondaryHouseCellID];
    [_searchListTableView registerClass:[AgentListNoSlideTableViewCell class] forCellReuseIdentifier:AgentCellID];
    [_searchListTableView registerClass:[ApartmentHotelListTableViewCell class] forCellReuseIdentifier:ApartmentHotelCellID];
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArr.count;
}
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([_currentStr isEqualToString:@"租房"]) {
        RentHouseListNoSlideTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:rentHouseCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary *dic = _dataArr[indexPath.row];
        RentHouseListModel *model = [RentHouseListModel modelWithDic:dic];
        cell.model = model;
        cell.tag = [model.itemid integerValue];
        return cell;
    }else if ([_currentStr isEqualToString:@"二手房"]) {
        SecondaryHouseListNoSlideTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:secondaryHouseCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary *dic = _dataArr[indexPath.row];
        SecondaryListModel *model = [SecondaryListModel modelWithDic:dic];
        cell.model = model;
        cell.tag = [model.itemid integerValue];
        return cell;
    }else if ([_currentStr isEqualToString:@"公寓酒店"]) {
        ApartmentHotelListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ApartmentHotelCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary *dic = _dataArr[indexPath.row];
        ApartmentHotelListModel *model = [ApartmentHotelListModel modelWithDic:dic];
        cell.model = model;
        cell.tag = [model.itemid integerValue];
        return cell;
    }else {
        AgentListNoSlideTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:AgentCellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSDictionary *dic = _dataArr[indexPath.row];
        AgentListModel *model = [AgentListModel modelWithDic:dic];
        cell.model = model;
        return cell;
    }
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([_currentStr isEqualToString:@"经纪人"]) {
        return 80;
    }else {
        return 100;
    }
}
//cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([_currentStr isEqualToString:@"租房"]) {
        RentHouseListNoSlideTableViewCell *cell = [_searchListTableView cellForRowAtIndexPath:indexPath];
        SecondaryDetailViewController *secondaryVC  = [[SecondaryDetailViewController alloc] init];
        secondaryVC.itemID = [NSString stringWithFormat:@"%ld", (long)cell.tag];
        [self.navigationController pushViewController:secondaryVC animated:YES];
    }else if ([_currentStr isEqualToString:@"二手房"]) {
        SecondaryHouseListNoSlideTableViewCell *cell = [_searchListTableView cellForRowAtIndexPath:indexPath];
        RentHouseDetailViewController *detailVC = [[RentHouseDetailViewController alloc] init];
        detailVC.itemid = [NSString stringWithFormat:@"%ld", (long)cell.tag];
        [self.navigationController pushViewController:detailVC animated:YES];
    }else if ([_currentStr isEqualToString:@"公寓酒店"]) {
        ApartmentHotelListTableViewCell *cell = [_searchListTableView cellForRowAtIndexPath:indexPath];
        ApartmentHotelDetailViewController *apartVC = [[ApartmentHotelDetailViewController alloc] init];
        apartVC.hotelID = [NSString stringWithFormat:@"%ld", (long)cell.tag];
        apartVC.titleStr = cell.model.housename;
        [self.navigationController pushViewController:apartVC animated:YES];
    }else {
        AgentDetailViewController *agentVC = [[AgentDetailViewController alloc] init];
        NSDictionary *dic = _dataArr[indexPath.row];
        AgentListModel *model = [AgentListModel modelWithDic:dic];
        agentVC.model = model;
        [self.navigationController pushViewController:agentVC animated:YES];
    }
}

#pragma mark - 数据请求

//上拉加载 数据请求
- (void)setFooterRefreshWithSearchText:(NSString *)searchText {
    [_searchListTableView.mj_footer beginRefreshing];
    self.searchListTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        //先判断当前搜索的模块 然后判断是否进行过文本搜索
        if ([_currentStr isEqualToString:@"租房"]) {
            if (_searchTextTag == 2) {

                NSString *str = searchText;
                str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
//                str = [str stringByTrimmingCharactersInSet:[NSCharacterSet URLQueryAllowedCharacterSet]];
                NSString *urlStr = [NSString stringWithFormat:@"%@page/%ld/areaid/%@/housename/%@/", rentHouseUrlStr, (long)_page, [[NSUserDefaults standardUserDefaults] objectForKey:cityID], str];
                //网络请求数据
                [NetRequest getWithURLString:urlStr parameters:nil progress:^(NSProgress *progress) {
                } success:^(id response) {
                    if ([response[@"flag"] isEqualToString:@"0"]) {
                        [self.searchListTableView.mj_footer endRefreshingWithNoMoreData];
                    }else {
                        for (NSDictionary *dic in response[@"chuzu"]) {
                            [_dataArr addObject:dic];
                        }
                        [_searchListTableView.mj_footer endRefreshing];
                        [_searchListTableView reloadData];
                    }
                    
                } failure:^(NSError *error) {
                    NSLog(@"%@", error);
                }];
            }else {
                [self.searchListTableView.mj_footer endRefreshing];
            }
        }else if ([_currentStr isEqualToString:@"公寓酒店"]) {
            if (_searchTextTag == 2) {
                NSString *str = searchText;
                str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];

                NSString *urlStr = [NSString stringWithFormat:@"%@page/%ld/areaid/%@/housename/%@/", hotelUrlStr, (long)_page, [[NSUserDefaults standardUserDefaults] objectForKey:cityID], str];
                //网络请求数据
                [NetRequest getWithURLString:urlStr parameters:nil progress:^(NSProgress *progress) {
                } success:^(id response) {
                    if ([response[@"flag"] isEqualToString:@"0"]) {
                        [self.searchListTableView.mj_footer endRefreshingWithNoMoreData];
                    }else {
                        for (NSDictionary *dic in response[@"list"]) {
                            [_dataArr addObject:dic];
                        }
                        [_searchListTableView.mj_footer endRefreshing];
                        [_searchListTableView reloadData];
                    }
                    
                } failure:^(NSError *error) {
                    NSLog(@"%@", error);
                }];
            }else {
                [self.searchListTableView.mj_footer endRefreshing];
            }
 
        }else if ([_currentStr isEqualToString:@"二手房"]) {
            if (_searchTextTag == 2) {
                NSString *str = searchText;
                str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
                NSString *urlStr = [NSString stringWithFormat:@"%@page/%ld/areaid/%@/housename/%@/", secondaryUrlStr, (long)_page, [[NSUserDefaults standardUserDefaults] objectForKey:cityID], str];
                //网络请求数据
                [NetRequest getWithURLString:urlStr parameters:nil progress:^(NSProgress *progress) {
                } success:^(id response) {
                    if ([response[@"flag"] isEqualToString:@"0"]) {
                        [self.searchListTableView.mj_footer endRefreshingWithNoMoreData];
                    }else {
                        for (NSDictionary *dic in response[@"chuzu"]) {
                            [_dataArr addObject:dic];
                        }
                        [_searchListTableView.mj_footer endRefreshing];
                        [_searchListTableView reloadData];
                    }
                    
                } failure:^(NSError *error) {
                    NSLog(@"%@", error);
                }];
            }else {
                [self.searchListTableView.mj_footer endRefreshing];
            }

        }else {
            if (_searchTextTag == 2) {
                NSString *str = searchText;
                str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
                NSString *urlStr = [NSString stringWithFormat:@"%@page/%ld/areaid/%@/key/%@/", agentUrlStr, (long)_page, [[NSUserDefaults standardUserDefaults] objectForKey:cityID], str];
                //网络请求数据
                [NetRequest getWithURLString:urlStr parameters:nil progress:^(NSProgress *progress) {
                } success:^(id response) {
                    if ([response[@"flag"] isEqualToString:@"0"]) {
                        [self.searchListTableView.mj_footer endRefreshingWithNoMoreData];;
                    }else {
                        for (NSDictionary *dic in response[@"jingjiren"]) {
                            [_dataArr addObject:dic];
                        }
                        [_searchListTableView.mj_footer endRefreshing];
                        [_searchListTableView reloadData];
                    }
                    
                } failure:^(NSError *error) {
                    NSLog(@"%@", error);
                }];
            }else {
                [self.searchListTableView.mj_footer endRefreshing];
            }
        }
    }];
}


#pragma mark - 代理协议
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    _page = 1;
    //搜索是否为空
    if (textField.text.length > 0) {
        _dataArr = [NSMutableArray array];
        _searchTextTag = 2;
        NSString *str = textField.text;
        str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];

        if ([_currentStr isEqualToString:@"租房"]) {
            NSString *urlStr = [NSString stringWithFormat:@"%@page/1/areaid/%@/housename/%@/", rentHouseUrlStr, [[NSUserDefaults standardUserDefaults] objectForKey:cityID], str];
            //网络请求数据
            [NetRequest getWithURLString:urlStr parameters:nil progress:^(NSProgress *progress) {
            } success:^(id response) {
                if ([response[@"flag"] isEqualToString:@"0"]) {
                    _dataArr = [NSMutableArray array];
                    [_searchListTableView reloadData];
                }else {
                    for (NSDictionary *dic in response[@"chuzu"]) {
                        [_dataArr addObject:dic];
                    }
                    [_searchListTableView reloadData];
                }
                
            } failure:^(NSError *error) {
                NSLog(@"%@", error);
            }];
        }else if ([_currentStr isEqualToString:@"公寓酒店"]) {
            NSString *urlStr = [NSString stringWithFormat:@"%@page/1/areaid/%@/housename/%@/", hotelUrlStr, [[NSUserDefaults standardUserDefaults] objectForKey:cityID], str];
            //网络请求数据
            [NetRequest getWithURLString:urlStr parameters:nil progress:^(NSProgress *progress) {
            } success:^(id response) {
                if ([response[@"flag"] isEqualToString:@"0"]) {
                    _dataArr = [NSMutableArray array];
                    [_searchListTableView reloadData];
                }else {
                    for (NSDictionary *dic in response[@"list"]) {
                        [_dataArr addObject:dic];
                    }
                    [_searchListTableView reloadData];
                }
            } failure:^(NSError *error) {
                NSLog(@"%@", error);
            }];
            
        }else if ([_currentStr isEqualToString:@"二手房"]) {
            NSString *urlStr = [NSString stringWithFormat:@"%@page/1/areaid/%@/housename/%@/", secondaryUrlStr, [[NSUserDefaults standardUserDefaults] objectForKey:cityID], str];
            //网络请求数据
            [NetRequest getWithURLString:urlStr parameters:nil progress:^(NSProgress *progress) {
            } success:^(id response) {
                if ([response[@"flag"] isEqualToString:@"0"]) {
                    _dataArr = [NSMutableArray array];
                    [_searchListTableView reloadData];
                }else {
                    for (NSDictionary *dic in response[@"chuzu"]) {
                        [_dataArr addObject:dic];
                    }
                    [_searchListTableView reloadData];
                }
            } failure:^(NSError *error) {
                NSLog(@"%@", error);
            }];
            
        }else if ([_currentStr isEqualToString:@"经纪人"]) {
            NSString *urlStr = [NSString stringWithFormat:@"%@page/1/key/%@/", agentUrlStr, str];
            //网络请求数据
            [NetRequest getWithURLString:urlStr parameters:nil progress:^(NSProgress *progress) {
            } success:^(id response) {
                if ([response[@"flag"] isEqualToString:@"0"]) {
                    _dataArr = [NSMutableArray array];
                    [_searchListTableView reloadData];
                }else {
                    for (NSDictionary *dic in response[@"jingjiren"]) {
                        [_dataArr addObject:dic];
                    }
                    [_searchListTableView reloadData];
                }
            } failure:^(NSError *error) {
                NSLog(@"%@", error);
            }];
        }
    }else {
        _searchTextTag = 1;
        _dataArr = [NSMutableArray array];
        [_searchListTableView reloadData];
        
    }
    [self setFooterRefreshWithSearchText:textField.text];
    [textField resignFirstResponder];
    return YES;
}

//创建视图
- (void)creatMainView {
    UIView *superView = self.view;
    NSArray *arr = @[@"附近房源", @"二手房", @"地图找房"];
    UILabel *label = [[UILabel alloc] init];
    label.text = @"搜索更多内容";
    label.font = [UIFont systemFontOfSize:20 weight:15];
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor colorWithRed:0.3222 green:0.3222 blue:0.3222 alpha:1.0];
    [self.view addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(superView.mas_top).offset(150);
        make.width.equalTo(@150);
        make.centerX.equalTo(superView.mas_centerX);
        make.height.equalTo(@40);
    }];
    UIStackView *viewStackView = [[UIStackView alloc] init];
    [self.view addSubview:viewStackView];
    [viewStackView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.top.equalTo(label.mas_bottom).offset(30);
    make.size.mas_equalTo(CGSizeMake(260, 100));
     make.centerX.equalTo(superView.mas_centerX);
    }];
    /* 布局方向 */
    viewStackView.axis = UILayoutConstraintAxisHorizontal;
    /* 间距 */
    viewStackView.spacing = 30.0f;
    /* 每个视图之间的关系 */
    viewStackView.distribution = UIStackViewDistributionFillEqually;
    /* 对齐方式 */
    viewStackView.alignment = UIStackViewAlignmentFill;
    for (int i = 0; i < 3; i++) {
        ImageViewAndLabelView *view = [[ImageViewAndLabelView alloc] init];
        [view.logoImageView addTarget:self action:@selector(detailPush:) forControlEvents:UIControlEventTouchUpInside];
        view.logoImageView.tag = i;
        view.descriptionLabel.text = arr[i];
        _str = view.descriptionLabel.text;
        [viewStackView addArrangedSubview:view];    }
}
//点击事件
- (void)detailPush:(UIButton *)button {
    switch (button.tag) {
        case 0:
            NSLog(@"附近房源");
            break;
        case 1:
            NSLog(@"二手房");
            break;
        case 2:
            NSLog(@"地图找房");
            break;
        default:
            break;
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
